const ports = new Set()
let currentMusic = null

self.onconnect = e => {
  const port = e.ports[0]
  ports.add(port)

  if (currentMusic) {
    port.postMessage({type: 'switch', music: currentMusic})
  }

  port.onmessage = event => {
    const {type, music} = event.data

    if (type === 'switch') {
      currentMusic = music
      ports.forEach(p => {
        p.postMessage({type: 'switch', music: currentMusic})
      })
    }

    if (type === 'play') {
      ports.forEach(p => {
        p.postMessage({type: 'play', music: music})
      })
    }
  }

  port.addEventListener('close', () => {
    ports.delete(port)
  })

  port.start()
}
